#!/bin/csh 
####################################################################################
## Creat large-forcing data for SPARTICUS 
## 
## Original data from ARM website: 
## http://www.arm.gov/news/data/post/20319 
##
## Steps: 
## 
## (1) Change variable name 
## (2) Change units 
## (3) Change additional information 
## 
## See scm_forcing_format.ncl for details  
## 
## Author: Kai Zhang (kai.zhang@pnnl.gov) 
## 
####################################################################################

setenv basedate 20091201 

###########################
## Jan
###########################

 foreach yymmdd (20091201 20100101 20100201 20100301 20100401 20100501 20100601) 

 echo ''
 echo ''
 echo ''
 echo '************************************************************************'
 echo 'Date : ' ${yymmdd} 

 rm -f sgp_${yymmdd}_cam5_v2.nc
 rm -f tmp_${yymmdd}_cam5.nc

 echo 'Invert Latitude '

 ncrcat -v lat,lon -x v2_sgp_${yymmdd}.nc tmp_${yymmdd}_cam5.nc
 cdo invertlev tmp_${yymmdd}_cam5.nc sgp_${yymmdd}_cam5_v2.nc

cat > loadit << EOF
  fna = "sgp_${yymmdd}_cam5_v2.nc"
EOF

 echo 'Call scm_forcing_format_6m.ncl ' 

 ncl scm_forcing_format_6m.ncl

end


###########################
## Merge files 
###########################

 rm -f tmp_2010_cam5.nc 
 rm -f sgp_2010_cam5_v2.nc 

 echo 'Merging 6 month data' 

 cdo mergetime sgp_20091201_cam5_v2.nc sgp_20100101_cam5_v2.nc sgp_20100201_cam5_v2.nc sgp_20100301_cam5_v2.nc sgp_20100401_cam5_v2.nc sgp_20100501_cam5_v2.nc sgp_20100601_cam5_v2.nc tmp_2010_cam5.nc 

 echo 'Add lat, lon, tsec' 

 ncrcat -v lat,lon,tsec,lev -x tmp_2010_cam5.nc sgp_2010_cam5_v2.nc 


###########################
## Creat NCL script 
###########################

cat > scm_forcing_format_merge_6m.ncl << EOF

  ;;......................................... 
  ;; Input data 
  ;;......................................... 
  fna = "sgp_2010_cam5_v2.nc"
  fnb = "sgp_20100401_shaocheng.nc"

  fla = addfile(fna,"w")
  flb = addfile(fnb,"r")

  ;;......................................... 
  ;; Base date
  ;;......................................... 
  bdate = flb->bdate
  bdate = (/ ${basedate} /)
  fla->bdate=bdate

  ;;......................................... 
  ;; Lat & Lon
  ;;......................................... 
  lat = 36.605
  lat!0 = "lat"
  lat&lat = 36.605

  lon = -97.485
  lon!0 = "lon"
  lon&lon = -97.485

  fla->lon=lon
  fla->lat=lat
  time = fla->time

  lev = flb->lev
  fla->lev=lev

  nt = dimsizes(time)

  tsec = new(nt,"double")
  tsec!0 = "time"
  tsec&time = time
  tsec@long_name = "time" ;
  tsec@units = "seconds" ;

  tsec = (/ fspan(0.,3600.*nt,nt)   /)

  fla->tsec=tsec

EOF

 echo 'Call scm_forcing_format_merge_6m.ncl '

 ncl scm_forcing_format_merge_6m.ncl


###########################
## Clean up 
###########################

 rm -f sgp_????????_cam5_v2.nc 
 rm -f tmp_*.nc 


